﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.WXT.Infrstructre
{
    public class BaseRepository<T>:IBaseRepository<T> where T : class,new()
    {
        public SystemWxtDbContext db;

        public BaseRepository(SystemWxtDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Add(T entity)
        {
            db.Set<T>().Add(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAll()
        {
            return await db.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> GetBaby(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 修改 逻辑删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Update(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Updatees(List<T> entity)
        {
            db.Set<T>().UpdateRange(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 添加返回Id
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddAsyncs(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            await db.SaveChangesAsync();
            return (int)entity.GetType().GetProperty("craftManageId")?.GetValue(entity);
        }
    }
}
